package itqf.dao;


import itqf.dao.impl.UserDao;
import itqf.entity.Users;
import itqf.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

/**
 * com.itqf.dao
 * 2020/9/14
 */
public class UserDaoImpl implements UserDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDateSource());
    @Override
    public Users findUser(String username, String upassword) {
        String sql = "select u_id as id,u_name as username,u_password as upassword,u_status as ustatus from user where u_name=? and u_password=?";
        Object[] params = {username,upassword};
        try {
            return qr.query(sql,new BeanHandler<>(Users.class),params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int insert(Users user) {
        String sql = "insert into user(u_name,u_password,u_email,u_sex,u_status,u_code,u_role) values(?,?,?,?,?,?,?)";
        Object[] params = {user.getUsername(),user.getUpassword(),user.getUemail(),user.getUsex(),user.getUstatus(),user.getUcode(),user.getUrole()};
        try {
            return  qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int activeAccount(String c) {
        String sql = "select u_status from user where u_code=?";
        try {
            Object o = qr.query(sql, new ScalarHandler(), c);
            if(o == null){
                return -1;
            }
            return (Integer)o;


        } catch (SQLException e) {
           throw  new RuntimeException(e);
        }
    }

    @Override
    public int updateAccount(String code) {
        String sql = "update user set u_status=1,u_code=null where u_code=?";

        try {
            return qr.update(sql, code);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Users checkName(String username) {
        String sql = "select u_name as username,u_password as upassword,u_status as ustatus from user where u_name=?";
        try {
            return qr. query(sql,new BeanHandler<>(Users.class),username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
